package config

import (
	"fmt"
	"gitee.com/baizhige/go-server-tempalte/common/log"
	"gopkg.in/yaml.v3"
	"os"
)

func Init(project string) {
	workDir, err := os.Getwd()
	if err != nil {
		os.Exit(1)
	}
	active := os.Getenv(ActiveEnvKey)
	if active == "" {
		fmt.Println("must set ", ActiveEnvKey, " environment variable, example:", "dev ,", "test ,", "staging ,", "production")
		//os.Exit(1)
		active = "dev"
		log.Warn("Active is not config, use dev")
	}
	node := os.Getenv(NodeEnvKey)
	if node == "" {
		log.Warn("Node is not config, use default")
		node = "default"
	}

	ConfigureFile := fmt.Sprint(workDir + "\\" + active + ".yml")
	fmt.Println("config file:" + ConfigureFile)
	reader, err := os.Open(ConfigureFile)
	if err != nil {
		ConfigureFile = fmt.Sprint(workDir + "\\app\\" + project + "\\" + active + ".yml")
		fmt.Println("config file:" + ConfigureFile)
		reader, err = os.Open(ConfigureFile)
		if err != nil {
			fmt.Println("open file error", err)
			os.Exit(1)
		}
	}
	defer reader.Close()

	err = yaml.NewDecoder(reader).Decode(&Project)
	if err != nil {
		fmt.Println("parse file error", err)
		os.Exit(1)
	}
	Project.Name = project
	Project.Active = active
	Project.Node = node
	log.Info("init config success!")
}
